package com.viewpagerindicator.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.viewpagerindicator.sample.util.ACache;

import java.util.Arrays;

/**
 * Created by zhao on 2015/11/11.
 */
public class PrintActivity extends AppCompatActivity {
    private final static String TAG = PrintActivity.class.getSimpleName();
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    public static final String CONTENT_2_PRINT = "CONTENT_2_PRINT";
    private BluetoothLeService mBluetoothLeService;
    private boolean mConnected = false;
    String mDeviceAddress=null;
    String content2Print=null;
    TextView messageShow;
    TextView progressTitle;
    ACache mCache ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.print_layout);
        mDeviceAddress = getIntent().getStringExtra(EXTRAS_DEVICE_ADDRESS);
        content2Print = getIntent().getStringExtra(CONTENT_2_PRINT);
        mCache=ACache.get(this);
        content2Print=mCache.getAsString(content2Print);
        if(mDeviceAddress==null){
            showDialog(getString(R.string.the_device_unvaliable),getString(R.string.click_ok_to_exit));
        }
        messageShow= (TextView) findViewById(R.id.show_message);
        progressTitle= (TextView) findViewById(R.id.progress_title);
        messageShow.setMovementMethod(ScrollingMovementMethod.getInstance());
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        Log.d(TAG, "Try to bindService=" + bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE));
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }
    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                showDialog(getString(R.string.the_service_unvaliable),getString(R.string.click_ok_to_exit));
            }
            mBluetoothLeService.connect(mDeviceAddress);
            Log.e(TAG, "mBluetoothLeService is okay");
            // Automatically connects to the device upon successful start-up initialization.
            //mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    //                        or notification operations.
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {  //连接成功
                toLog("蓝牙设备连接成功,等待通信状态");
                Log.e(TAG, "Only gatt, just wait");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { //断开连接
                toLog("蓝牙断开连接,点击确定退出此页面后检查设备并重新进入。");
                showDialog("蓝牙断开连接", "点击确定退出此页面");
                mConnected = false;
            }else if(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) //可以开始干活了
            {
                toLog("连接正常，可以正常通信,发送Pc;指令\r\n等待接收数据指令");
                write2Bluetooth("PC;");
                mConnected = true;
                Log.e(TAG, "In what we need");
            }else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { //收到数据
                String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
                toLog("收到指令："+data);
                if(data!=null&&data.equals("C")){
                    toLog("数据发送中,请勿退出...");
                    write2Bluetooth(content2Print);
                }
                Log.e(TAG, "RECV DATA");
            }else if(BluetoothLeService.ACTION_DATA_WRITED.equals(action)){
                write2Bluetooth("success");
            }
        }
    };
    public void write2Bluetooth(String content){
        final byte[] cbytes=content.getBytes();
        if(cbytes.length>20){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    byte[] sendBytes=new byte[20];
                    int i=0;
                    while(true) {
                        if(i>=cbytes.length){
                            break;
                        }
                        int to=20;
                        if((cbytes.length-i)<20){
                            to=cbytes.length-i;
                        }
                        sendBytes=Arrays.copyOfRange(cbytes,i,i+to);
                        i=i+20;
                        try {
                            mBluetoothLeService.writeValue(sendBytes);
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                            break;
                        }
                        final int nowSended=i;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressTitle.setText(nowSended+"/"+cbytes.length);
                            }
                        });
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toLog("发送完毕! 您可以：继续等待打印 或者 点击返回键退出.");
                            showDialogToExit();
                        }
                    });
                }}).start();
        }else{
            mBluetoothLeService.writeValue(cbytes);
        }
    }
    private static IntentFilter makeGattUpdateIntentFilter() {                        //注册接收的事件
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothDevice.ACTION_UUID);
        return intentFilter;
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
        unbindService(mServiceConnection);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //this.unregisterReceiver(mGattUpdateReceiver);
        //unbindService(mServiceConnection);
        if(mBluetoothLeService != null)
        {
            mBluetoothLeService.close();
            mBluetoothLeService = null;
        }
        Log.d(TAG, "We are in destroy");
    }
    public void showDialog(String title,String msg){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(msg);
        builder.setNegativeButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                finish();
            }
        });
        builder.show();
    }
    public void toLog(String msg){
        messageShow.append("\r\n" + msg);
        int offset=messageShow.getLineCount()*messageShow.getLineHeight();
        if(offset>messageShow.getHeight()){
            messageShow.scrollTo(0,offset-messageShow.getHeight());
        }
    }
    public void showDialogToExit(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_title);
        builder.setMessage(R.string.print_over);
        builder.setNegativeButton(R.string.print_over_return, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                finish();
            }
        });
        builder.setPositiveButton(R.string.print_over_continue, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
    public void back(View view){
        finish();
    }
}
